import { PrismaService } from './../prisma/prisma.service'
import { Injectable } from '@nestjs/common'
import { MailerService } from '@nestjs-modules/mailer'
import dayjs from 'dayjs'
export interface MailOptionsType {
  subject: string
  code: string | number
  target: string
  date: string
}
@Injectable()
export class emailService {
  constructor(private MailerService: MailerService, private prisma: PrismaService) {}
  async sendEmailCode(data: MailOptionsType) {
    const sendOptions = {
      to: data.target,
      subject: data.subject,
      template: `validate.code.ejs`,
      context: {
        code: data.code,
        date: data.date,
        sign: '这是系统自动发送的邮件，您无需回复',
      },
    }
    return await this.MailerService.sendMail(sendOptions)
  }
  async storageCode({ email, code, time }) {
    return await this.prisma.code.upsert({
      where: { email: email },
      create: { email, code, time },
      update: { email, code, time },
    })
  }
  async ifCodeLimt(email: string): Promise<boolean> {
    const res = await this.prisma.code.findUnique({ where: { email } })
    if (!res) {
      return true
    }
    const time = dayjs(res.time).format('YYYY-MM-DD HH:mm:ss')
    return dayjs().diff(time, 'minutes') >= 1
  }
}
